<template>
  <view>
    <!-- 加载中蒙版 -->
    <qmy-mask-load :dataLoaded="dataLoaded"></qmy-mask-load>
    
    <!-- #ifdef MP-WEIXIN -->
    <!-- 顶部导航 -->
    <qmy-custom-navbar bacColor="0"></qmy-custom-navbar>
    <!-- #endif -->
    <image
        :src="!user_id?userInfo.homepage || 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/userpersonBg.jpg':userInfo_public.homepage || 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/userpersonBg.jpg'"
        class="userBg" mode="aspectFill" :style="{height:menuObject.top + menuObject.height +210 + 'px'}"></image>
    <view class="userCenter bac-col-f pos-abso" :style=" {top:menuObject.top + menuObject.height +190 + 'px' }">
      <view class="ping-30">
        <view class="flex-dir-row ali-item-cen flex-x-bet">
          <image class="br-200 user-img"
                 :src="!user_id
					        ? (userInfo.avatar? userInfo.avatar : 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg')
					        : (userInfo_public.avatar ? userInfo_public.avatar : 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg')"
                 mode="aspectFill">
          </image>
          <!-- 自己的主页显示编辑资料按钮 -->
          <view v-if="userInfo.id == user_id || !user_id" @click="$NavigateTo('/qmy_user/user/userPersonal')"
                class="fs-26 col-00ba31 br-200 edit-btn">
            编辑资料
          </view>
          <!-- 他人主页显示关注和私信按钮 -->
          <view v-else class="flex-dir-row">
            <view @click="toggleFollow" 
                  class="fs-26 br-200 mr-15 follow-btn"
                  :class="isFollowing ? 'following-btn' : 'not-following-btn'">
              {{ isFollowing ? '已关注' : '关注' }}
            </view>
            <view @click="goToChat" 
                  class="fs-26 col-00ba31 br-200 chat-btn">
              私信
            </view>
          </view>
        </view>
        <view class="flex-dir-row ali-item-cen mt-10">
          <text
              class="fs-50 fw-600 mr-30">
            {{ !user_id ? userInfo.nickname || '匿名用户' : userInfo_public.nickname || '匿名用户' }}️
          </text>
        </view>
        <view class="flex-dir-row ali-item-cen mt-10">
          <view class="iconfont" :class="{
					  'gender-icon-unknown': (!user_id ? !userInfo.gender : !userInfo_public.gender),
					  'ic-nan gender-icon-male': (!user_id ? userInfo.gender == 1 : userInfo_public.gender == 1),
					  'ic-nv gender-icon-female': (!user_id ? userInfo.gender == 2 : userInfo_public.gender == 2)
					}">
            <text :class="!userInfo.gender && !userInfo_public.gender?'':'ml-10'"
                  class=" col-f">
              {{
                !user_id ? userInfo.birthday ? getAge(userInfo.birthday) : '未设置生日' : userInfo_public.birthday ? getAge(userInfo_public.birthday) : '未设置生日'
              }}
            </text>
            <text class="ml-10 col-f fw-900">·</text>
            <text
                class="ml-10 col-f">
              {{ !user_id ? userInfo.city || '未设置城市' : userInfo_public.city || '未设置城市' }}
            </text>
          </view>
        </view>
        <view class="fs-30 col-54 mt-10">
          {{ !user_id ? userInfo.signature || '未设置签名' : userInfo_public.signature || '未设置签名' }}️
        </view>
        <view class="flex-dir-row ali-item-cen mt-10">
          <view class="flex-dir-row ali-item-bas mr-20">
            <text class="fw-600 fs-38">{{ activityCount }}</text>
            <text class="fs-26 col-54 ml-5">活动</text>
          </view>
          <view class="flex-dir-row ali-item-bas mr-20">
            <text class="fw-600 fs-38">{{ !user_id ? userInfo.followingCount : userInfo_public.followingCount }}</text>
            <text class="fs-26 col-54 ml-5">关注</text>
          </view>
          <view class="flex-dir-row ali-item-bas mr-20">
            <text class="fw-600 fs-38">{{ !user_id ? userInfo.followersCount : userInfo_public.followersCount }}</text>
            <text class="fs-26 col-54 ml-5">粉丝</text>
          </view>
        </view>
      </view>
      <view class="bor-bottom-f3 mt-20">
        <v-tabs :scroll="false" :zIndex="1" bgColor="#ffffff00" pillsColor="#ffffff00" fontSize="30rpx"
                pillsStyle="box" activeFontSize="32rpx" lineHeight="4rpx"
                activeColor="linear-gradient(to right, #1e1e1e, #1e1e1e)"
                color="linear-gradient(to right, #616161, #616161)" bold lineColor="#14cc60" v-model="current"
                :tabs="tabs" @change="changeTab"></v-tabs>
        <view class="bac-col-fa ping-30">
          <view v-if="current == 0" class="animate__fadeInRight dh-0-6s">
            <view class="flex-dir-row ali-item-cen fs-26 col-87 mb-30">
              <view @click="switchState(index)" v-for="(item, index) in activeStateList" :key="index"
                    class="br-200 state-btn text-ali-c mr-20 box-nw"
                    :class="activeState == index ? 'bac-col-00b col-f' : ''">
                {{ item }}
              </view>
            </view>
            <view v-if="activityData.length == 0 || filteredActivityData.length == 0" class="pos-rela"
                  style="height: 37vh;">
              <!-- 如果活动列表为空 -->
              <view class="activity-empty-box">
                <image class="activity-empty-image"
                       src="https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/activity-mepty.png"
                       mode="scaleToFill"/>
                <view class="fs-28 fw-600">暂无活动</view>
              </view>
            </view>
            <scroll-view v-else scroll-y class="animate__fadeInRight dh-0-6s h-60-vh">
              <view v-for="(item,index) in filteredActivityData" :key="index"
                    class="bac-col-f br-20 ping-20"
                    :class="index != activityData.length - 1 ? 'mb-20' : ''">
                <view class="flex-dir-row ali-item-cen"
                      @click="$NavigateTo(`/pages/detail/detail?id=${item._id}`)">
                  <view class="img-190 pos-rela">
                    <image class="br-20 img-190" :src="item.imgs[0].src" mode="aspectFill">
                    </image>
                    <view class="pos-abso brtl-20 brbr-20  fs-22  ping-6-10"
                          style="top: 0;left: 0;z-index: 2;"
                          :class="item.signup_start_time > Date.now()?'bac-col-fa col-0a2e365e':item.signup_start_time < Date.now() && item.signup_end_time > Date.now() ? 'bac-col-00b col-f' : item.start_time < Date.now() && item.end_time > Date.now() ? 'bac-col-ffd col-f' : item.start_time > Date.now() ? 'bac-col-4e col-f' : 'bac-col-fa col-0a2e365e'">
                      {{
                        item.signup_start_time > Date.now() ? '未开启' : item.signup_start_time < Date.now() && item.signup_end_time > Date.now() ? '报名中' : item.start_time < Date.now() && item.end_time > Date.now() ? '进行中' : item.start_time > Date.now() ? '待进行' : '已结束'
                      }}
                    </view>
                  </view>
                  <view class="fs-24 flex-dir-col flex-x-bet ml-20" style="height: 180rpx;">
                    <view class="fs-34 fw-600 text-element-1">{{ item.name }}</view>
                    <view class="flex-dir-row ali-item-cen overflow-h mt-10">
                      <view v-for="tag in item.tags" :key="tag" class="text-tips bac-col-00b">
                        {{ tag }}
                      </view>
                    </view>
                    <view class="flex-dir-row ali-item-cen col-b1">
                      <view class="iconfont ic-shijianxuanzeqi mr-10"></view>
                      <view
                          v-if="item.signup_start_time < Date.now() && item.signup_end_time > Date.now()">
                        {{ $formatDate(item.signup_start_time) }} -
                        {{ $formatDate(item.signup_end_time) }}
                      </view>
                      <view v-else>{{ $formatDate(item.start_time) }} -
                        {{ $formatDate(item.end_time) }}
                      </view>
                    </view>
                    <view class="flex-dir-row ali-item-cen col-b1">
                      <view class="iconfont ic-weizhi mr-10"></view>
                      <view class="text-element-1">{{ item.location }}</view>
                    </view>
                  </view>
                </view>
                <view class="flex-dir-row flex-x-bet ali-item-cen pt-20 mt-20 bor-top-f3">
                  <view class="flex-dir-row ali-item-cen  col-b1">
                    <view class="flex-dir-row ali-item-cen">
                      <image v-for="(usimg,its) in item.user_info.slice(0,4)" :key="its"
                             :src="usimg.user_avatar || 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg'"
                             :style="{marginLeft: its == 0?0:'-20rpx'}" mode="aspectFill"
                             class="img-50 br-200">
                      </image>
                    </view>
                    <view class="ml-10 fs-24">
                      {{ item.user_info.length ? item.user_info.length + '人已报名' : '' }}
                    </view>
                  </view>
                  <view @click="$NavigateTo(`/pages/detail/detail?id=${item._id}`)"
                        class="fs-26 br-200 text-ali-c fw-600 btn-bg">
                    <view class="gradient-text">预览</view>
                  </view>
                </view>
              </view>
              <qmy-logo></qmy-logo>
            </scroll-view>
          </view>
          <scroll-view scroll-y v-if="current == 1" class="animate__fadeInLeft dh-0-6s h-60-vh pos-rela">
            <view v-if="circleData.length == 0" class="pos-rela" style="height: 37vh;">
              <!-- 如果圈子列表为空 -->
              <view class="activity-empty-box">
                <image class="activity-empty-image"
                       src="https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/circle-empty.png"
                       mode="scaleToFill"/>
                <view class="fs-28 fw-600">暂无圈子</view>
              </view>
            </view>
            <view v-else>
              <view v-for="(item,index) in circleData" :key="index"
                    class="bac-col-f br-20 mt-10 pos-rela mb-30 animate__fadeIn dh-0-4s"
                    style="z-index: 1;">
                <view class="ping-30">
                  <view class="flex-dir-row flex-x-bet ali-item-cen">
                    <view class="flex-dir-row ali-item-cen">
                      <qmy-gender-border :gender="item.user_gender"
                                         :avatar="item.user_avatar || 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg'"
                                         :avatarWidth="75 + 'rpx'"
                                         :avatarHeight="75 + 'rpx'"></qmy-gender-border>
                      <view class="ml-20">
                        <view class="fs-26 fw-600 flex-dir-row ali-item-cen">
                          <view class="text-element-1">{{ item.user_name || '匿名用户' }}</view>
                          <view v-if="item.is_essence" class="fs-20 highlighted">精选</view>
                        </view>
                        <view class="fs-24 col-b1 mt-5">
                          {{ $timeFormat(item.last_modify_date || item.publish_date) }}
                        </view>
                      </view>
                    </view>
                  </view>
                  <view class="mt-20"
                        @click="$NavigateTo(`/pages/detail/articleDetail?id=${item._id}`)">
                    <view class="fs-28 text-element-4">
                      {{ item.title }}
                    </view>
                    <image v-if="item.thumbnail.length == 1" class="br-20 mt-20 image-280"
                           :src="item.thumbnail[0]" mode="aspectFill">
                    </image>
                    <view v-else-if="item.thumbnail.length == 2" class="flex-dir-row flex-x-bet">
                      <image v-for="(url,its) in item.thumbnail"
                             :class="its == 0?'brtl-20 brbl-20':'brtr-20 brbr-20'" :key="its"
                             class="mt-20 image-3125" :src="url" mode="aspectFill">
                      </image>
                    </view>
                    <view v-else-if="item.thumbnail.length >= 3" class="flex-dir-row flex-x-bet">
                      <image v-for="(url,its) in item.thumbnail.slice(0,3)"
                             :class="its == 0?'brtl-20 brbl-20':its == 1?'':'brtr-20 brbr-20'"
                             :key="its" class="mt-20 image-205" :src="url" mode="aspectFill">
                      </image>
                    </view>
                  </view>
                  <view>
                    <view class="flex-x-bet ali-item-cen flex-dir-row mt-20">
                      <view>
                        <view v-if="item.activity_id"
                              @click="$NavigateTo(`../detail/detail?id=${item.activity_id}`)"
                              class="br-200 flex-dir-row ali-item-cen border-bf padding-5-15">
                          <image class="image-28" :src="item.activity_img[0].src"
                                 mode="aspectFill">
                          </image>
                          <view class="fs-26 ml-10 text-element-1">{{ item.activity_name }}
                          </view>
                        </view>
                      </view>
                      <view class="flex-dir-row ali-item-cen col-87">
                        <view class="flex-dir-row ali-item-cen">
                          <view class="iconfont ic-talk-line fs-46"></view>
                          <view class="fs-28 ml-5">{{ item.comment_count || 0 }}</view>
                        </view>
                        <view @click="likeCircle(item._id)"
                              class="flex-dir-row ali-item-cen ml-20">
                          <view class="iconfont fs-46 "
                                :class="item.like_user_id.includes(userInfo.id)?'ic-nice col-00ba31':'ic-nice-line col-87'">
                          </view>
                          <view class="fs-28 ml-5">{{ item.like_user_id.length || 0 }}</view>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
              <qmy-logo></qmy-logo>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  store,
  mutations
} from '@/utils/store.js'

import {getOtherUserInfo, userInfo, followUser as followUserApi, unfollowUser as unfollowUserApi, checkFollowStatus as checkFollowStatusApi} from '@/api/user/user.js'

import {getActivityCountApi} from '@/api/activity/activity.js'

export default {
  data() {
    return {
      // #ifdef MP-WEIXIN
      menuObject: uni.getMenuButtonBoundingClientRect(),
      // #endif
      // #ifndef MP-WEIXIN
      menuObject: 0,
      // #endif
      current: 0,
      tabs: ['活动', '圈子'],
      activeState: 0,
      activeStateList: ['全部', '进行中', '报名中', '已结束'],
      user_id: '',
      activityCount: 0,
      circleLikeCount: 0,
      circleCount: 0,
      activityData: [],
      circleData: [],
      dataLoaded: false,
      userInfo_public: {},
      gender: ['未知', '男', '女'],
      isFollowing: false // 是否已关注该用户
    }
  },
  computed: {
    userInfo() {
      return store.userInfo //用户信息
    },
    filteredActivityData() {
      const now = Date.now(); // 缓存当前时间戳
      return this.activityData.filter(item => {
        switch (this.activeState) {
          case 0:
            return true;
          case 1:
            return item.start_time < now && item.end_time > now;
          case 2:
            return item.signup_start_time < now && item.signup_end_time > now;
          case 3:
            return item.end_time < now;
          default:
            return true;
        }
      });
    }
  },
    onLoad(e) {
    console.log('页面加载开始, dataLoaded:', this.dataLoaded);
    console.log('接收到的参数:', e);
    
    // 获取传入的用户ID
    if (e.usid) {
      this.user_id = e.usid;
      console.log('设置用户ID:', this.user_id);
    }
    
    this.initPage();
  },
  onShow() {
    console.log('页面显示, dataLoaded:', this.dataLoaded);
    // 每次页面显示时都重新获取用户信息
    this.initPage();
  },
  methods: {
    // 初始化页面
    initPage() {
      console.log('初始化页面开始');
      
      // 重置加载状态
      this.dataLoaded = false;
      
      // 获取用户信息（内部会调用其他数据获取方法）
      this.getUserInfos();
      
      // 添加一个保险的延时设置，确保页面能显示
      setTimeout(() => {
        if (!this.dataLoaded) {
          console.log('延时设置dataLoaded为true');
          this.dataLoaded = true;
        }
      }, 3000);
    },
    // 获取对应用户活动数量
    getMyActivityCount() {
      let data = {
        userId: this.user_id
      }
      getActivityCountApi(data).then((res) => {
        this.activityCount = res.data.data;
        this.$emit('refreshState', false) //重置刷新状态
      }).catch((err) => {
        this.$emit('refreshState', false) //重置刷新状态
        console.error('遇到错误:', err); // 打印错误信息
        let {
          code,
          msg
        } = this.$parseError(err); // 调用公共解析方法
        this.$Toast(msg);
        setTimeout(() => {
          if (code === 401) {
            this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
          }
        }, 1000);
      });
    },
    // 获取对应用户信息
    getUserInfos() {
      console.log('开始获取用户信息, user_id:', this.user_id);

      if (!this.user_id) {
        // 没有传入用户ID，获取当前登录用户信息
        console.log('获取当前用户信息');
        userInfo().then((res) => {
          console.log('获取当前用户信息成功:', res);

          if (res.data.data) {
            // 更新store中的用户信息
            mutations.updateUserInfo(res.data.data);
            
            // 获取用户统计数据
            this.getMyActivityCount();
            // this.getMyCircleLikeCount();
            // this.getMyCircleCount();
            // this.getUserActivityData();
            // this.getUserCircleData();
          }

          this.dataLoaded = true;
          this.$nextTick(() => {
            this.$forceUpdate();
          });

        }).catch((err) => {
          console.error('获取当前用户信息失败:', err);
          this.dataLoaded = true;
          this.$forceUpdate();

          console.error('API调用失败:', err);
          this.$Toast(err.message || '获取用户信息失败');
          
          if (err.message && err.message.includes('401')) {
            this.$Toast('登录已过期，请重新登录');
            mutations.logout();
            setTimeout(() => {
              this.$NavigateTo('/qmy_user/login');
            }, 1000);
          }
        });
      } else {
        // 传入了用户ID，获取指定用户的公开信息
        console.log('获取指定用户信息, ID:', this.user_id);
        let params = {
          userId: this.user_id
        };
        getOtherUserInfo(params).then((res) => {
          console.log('获取其他用户信息成功:', res);
          
                     if (res.data.data) {
             // 设置其他用户的信息
             this.userInfo_public = res.data.data;
             
             // 获取该用户的统计数据
             this.getMyActivityCount();
             // this.getMyCircleLikeCount();
             // this.getMyCircleCount();
             // this.getUserActivityData();
             // this.getUserCircleData();
             
             // 检查关注状态
             this.checkFollowStatus();
           }

          this.dataLoaded = true;
          this.$nextTick(() => {
            this.$forceUpdate();
          });

        }).catch((err) => {
          console.error('获取其他用户信息失败:', err);
          this.dataLoaded = true;
          this.$forceUpdate();

          console.error('API调用失败:', err);
          this.$Toast(err.message || '获取其他用户信息失败');
          
          if (err.message && err.message.includes('401')) {
            this.$Toast('登录已过期，请重新登录');
            setTimeout(() => {
              this.$NavigateTo('/qmy_user/login');
            }, 1000);
          }
        });
      }
    },


    // 获取对应用户圈子点赞数
    getMyCircleLikeCount() {
      this.$Route('get-private-data', true).getMyCircleLikeCount(this.user_id).then((res) => {
        this.circleLikeCount = res.data;
      }).catch((err) => {
        console.error('遇到错误:', err); // 打印错误信息
        let {
          code,
          msg
        } = this.$parseError(err); // 调用公共解析方法
        this.$Toast(msg);
      });
    },
    // 获取对应用户圈子数
    getMyCircleCount() {
      this.$Route('get-private-data', true).getMyCircleCount(this.user_id).then((res) => {
        this.circleCount = res.data;
      }).catch((err) => {
        console.error('遇到错误:', err); // 打印错误信息
        let {
          code,
          msg
        } = this.$parseError(err); // 调用公共解析方法
        this.$Toast(msg);
      });
    },
    // 获取对应用户的活动数据
    getUserActivityData() {
      this.$Route('get-private-data', true).getUserActivityData(this.user_id).then((res) => {
        this.activityData = res.data;
        this.dataLoaded = true;
      }).catch((err) => {
        console.error('遇到错误:', err); // 打印错误信息
        let {
          code,
          msg
        } = this.$parseError(err); // 调用公共解析方法
        this.$Toast(msg);
      });
    },
    // 获取对应用户的圈子列表
    getUserCircleData() {
      this.$Route('get-private-data', true).getUserCircleData(this.user_id).then((res) => {
        this.circleData = res.data;
      }).catch((err) => {
        console.error('遇到错误:', err); // 打印错误信息
        let {
          code,
          msg
        } = this.$parseError(err); // 调用公共解析方法
        this.$Toast(msg);
        setTimeout(() => {
          if (code === 401) {
            this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
          }
        }, 1000);
      });
    },
    changeTab(e) {
      this.current = e;
    },
    switchState(e) {
      this.activeState = e;
    },
    // 切换关注状态
    toggleFollow() {
      if (!this.userInfo.id) {
        this.$Toast('请先登录');
        this.$NavigateTo('/qmy_user/login');
        return;
      }
      
      if (this.isFollowing) {
        // 取消关注
        this.unfollowUser();
      } else {
        // 关注用户
        this.followUser();
      }
    },
    
    // 关注用户
    followUser() {
      // 这里调用关注接口
      const params = {
        followUserId: this.user_id
      };
      
      uni.showLoading({ title: '关注中...' });
      
      followUserApi(params).then((res) => {
        if (res.data.code === 200) {
          this.isFollowing = true;
          this.$Toast('关注成功');
          // 更新粉丝数
          if (this.userInfo_public.followersCount !== undefined) {
            this.userInfo_public.followersCount++;
          }
        } else {
          this.$Toast(res.data.message || '关注失败');
        }
      }).catch((err) => {
        console.error('关注失败:', err);
        this.$Toast('关注失败');
      }).finally(() => {
        uni.hideLoading();
      });
    },
    
    // 取消关注
    unfollowUser() {
      // 这里调用取消关注接口
      const params = {
        followUserId: this.user_id
      };
      
      uni.showLoading({ title: '取消关注中...' });
      
      unfollowUserApi(params).then((res) => {
        if (res.data.code === 200) {
          this.isFollowing = false;
          this.$Toast('已取消关注');
          // 更新粉丝数
          if (this.userInfo_public.followersCount !== undefined) {
            this.userInfo_public.followersCount--;
          }
        } else {
          this.$Toast(res.data.message || '取消关注失败');
        }
      }).catch((err) => {
        console.error('取消关注失败:', err);
        this.$Toast('取消关注失败');
      }).finally(() => {
        uni.hideLoading();
      });
    },
    
    // 跳转到私信页面
    goToChat() {
      if (!this.userInfo.id) {
        this.$Toast('请先登录');
        this.$NavigateTo('/qmy_user/login');
        return;
      }
      
      // 跳转到聊天页面
      this.$NavigateTo(`/pages/chat/chatDetail?targetUserId=${this.user_id}&targetUserName=${this.userInfo_public.nickname || '用户'}&targetUserAvatar=${this.userInfo_public.avatar || ''}`);
    },
    
    // 检查是否已关注该用户
    checkFollowStatus() {
      if (!this.user_id || !this.userInfo.id) {
        return;
      }
      
      // 这里调用检查关注状态的接口
      const params = {
        targetUserId: this.user_id
      };
      
      checkFollowStatusApi(params).then((res) => {
        if (res.data.code === 200) {
          this.isFollowing = res.data.data.isFollowing || false;
        }
      }).catch((err) => {
        console.error('检查关注状态失败:', err);
        // 失败时默认为未关注
        this.isFollowing = false;
      });
    },
    
    // 根据生日转换年龄
    getAge(birthday) {
      if (!birthday) return '未知'; // 防止 `null` 或 `undefined`

      // 兼容 `YYYY-MM-DD` 和 `YYYY.MM.DD` 格式，统一转换为 `YYYY-MM-DD`
      birthday = birthday.replace(/[.-]/g, '-');

      let dateParts = birthday.split('-');
      if (dateParts.length !== 3) return '未知'; // 格式错误

      let year = parseInt(dateParts[0]);
      let month = parseInt(dateParts[1]) - 1; // JavaScript 月份是 `0-11`
      let day = parseInt(dateParts[2]);

      let birthdays = new Date(year, month, day);
      if (isNaN(birthdays.getTime())) return '未知'; // 无效日期

      let now = new Date();
      let age = now.getFullYear() - birthdays.getFullYear();
      let monthDiff = now.getMonth() - birthdays.getMonth();
      let dayDiff = now.getDate() - birthdays.getDate();

      // 如果当前日期比生日早，说明还没满周岁，减掉一年
      if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
        age--;
        monthDiff += 12; // 补足月份
      }

      // 如果年龄 ≥ 1 岁，返回 `X岁`
      if (age >= 1) {
        return `${age}岁`;
      }

      // 计算月龄
      let totalMonths = (now.getFullYear() - birthdays.getFullYear()) * 12 + monthDiff;
      if (totalMonths >= 12) {
        return `${Math.floor(totalMonths / 12)}岁`;
      }
      if (totalMonths > 0) {
        return `${totalMonths}月`;
      }

      // 计算天数
      let timeDiff = now.getTime() - birthdays.getTime();
      let days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
      return days > 0 ? `${days}天` : '0天';
    },
  }
}

</script>

<style>
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.userBg {
  width: 100%;
  position: fixed;
  top: 0;
}

.user-img {
  width: 165rpx;
  height: 165rpx;
  border-radius: 50%;
  border: 6rpx solid #fff;
  margin-top: -112rpx;
  box-shadow: 0rpx 17rpx 27rpx #dcdcdc;
}

.edit-btn {
  border: 2rpx solid #14cc60;
  width: 300rpx;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
}

.userCenter {
  border-radius: 30rpx 30rpx 0 0;
  width: 100%;
  height: 70vh;
  /* #ifdef H5 */
  top: 400rpx;
  /* #endif */

}

.img-50 {
  width: 50rpx;
  height: 50rpx;
  border: 4rpx solid #ffffff;
}

.img-190 {
  width: 190rpx;
  height: 190rpx;
}


.text-tips {
  padding: 5rpx 10rpx;
  font-size: 24rpx;
  border-radius: 10rpx;
  color: #ffffff;
  font-size: 20rpx;
  margin-right: 10rpx;
}

.image-75 {
  width: 75rpx;
  height: 75rpx;
}

.image-280 {
  height: 280rpx;
  max-width: 100%;
}

.image-205 {
  height: 205rpx;
  width: 205rpx;
}

.image-28 {
  width: 28rpx;
  height: 28rpx;
  border-radius: 5rpx;
}

.image-3125 {
  height: 260rpx;
  width: 312rpx;
}

.highlighted {
  background: #ffe75c;
  width: 65rpx;
  height: 32rpx;
  line-height: 32rpx;
  border-radius: 10rpx;
  color: #fff;
  text-align: center;
  margin-left: 10rpx;
}

.padding-5-15 {
  padding: 5rpx 15rpx;
}

.state-btn {
  width: 130rpx;
  height: 50rpx;
  line-height: 50rpx;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.state-btn:active {
  transform: scale(0.95);
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
}

.gender-icon-unknown {
  padding: 8rpx 15rpx;
  border-radius: 10rpx;
  font-size: 24rpx;
  text-align: center;
  background-color: #c1c1c1;
  color: #3e3e3e;
}

.gender-icon-male {
  padding: 8rpx 15rpx;
  border-radius: 10rpx;
  font-size: 24rpx;
  text-align: center;
  background-color: #b6d8ff;
  color: #3b9aff;
}

.gender-icon-female {
  padding: 8rpx 15rpx;
  border-radius: 10rpx;
  font-size: 24rpx;
  text-align: center;
  background-color: #feb3ca;
  color: #ff437e;
}

/* 关注和私信按钮样式 */
.follow-btn {
  width: 120rpx;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  transition: all 0.3s ease;
}

.not-following-btn {
  border: 2rpx solid #14cc60;
  color: #14cc60;
  background-color: transparent;
}

.following-btn {
  border: 2rpx solid #999;
  color: #999;
  background-color: transparent;
}

.chat-btn {
  border: 2rpx solid #14cc60;
  width: 120rpx;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  background-color: transparent;
}

.follow-btn:active,
.chat-btn:active {
  transform: scale(0.95);
  opacity: 0.8;
}
</style>
